process.chdir(process.cwd())
const argv = process.argv
const help = `运行状态: Anat status
停止命令: Anat stop
重启命令: Anat restart
启动命令: Anat 你的密钥`
const helpList = ['-h', '-help', '--help']
const signList = ['restart', 'status', 'stop', 'test'].concat(helpList)

// 接受控制信号
global.signFn = {
  restart() {
    udp.sendTo({ code: 'disconnect' })
    const { exec } = require('child_process')
    exec(process.argv.join(' '), { env: process.env })
    setTimeout(process.exit, 1)
  },
  stop() {
    udp.sendTo({ code: 'disconnect' })
    process.exit(1)
  },
  status() {
    fs.writeFileSync('.json', JSON.stringify({ rss: process.memoryUsage().rss, heap: process.memoryUsage().heapTotal, count: udp.count, ping: udp.ping, mtu: udp.mtu, pid: process.pid, last: Agl.getTime() }))
  },
  default() {
    fs.writeFileSync('.json', JSON.stringify(process.argv))
  }
}

const watchFn = () => {
  if (!fs.existsSync('.sign')) fs.writeFileSync('.sign', '', { encoding: 'utf8' })
  watchFn.last = Agl.getTime()
  fs.watch('.sign', { interval: 500 }, (type, filename) => {
    const sign = fs.readFileSync('.sign', { encoding: 'utf8' })
    if (!sign) return
    const nt = Agl.getTime()
    if (nt - watchFn.last < 100) return
    watchFn.last = nt
    if (signFn[sign]) signFn[sign]()
  })
}

if (!argv[2]) {
  fs.writeFileSync('.pid', process.pid + '')
  watchFn()
  if (fs.existsSync('.secret')) {
    Config.secret = fs.readFileSync('.secret', { encoding: 'utf8' })
  }
  return udpSer()
  // console.log('请输入您的密钥')
  // process.stdin.setEncoding('utf8')
  // process.stdin.on('readable', () => {
  //   let chunk
  //   while ((chunk = process.stdin.read()) !== null) {
  //     Config.secret = chunk.substr(0, chunk.length - 1)
  //     udpSer()
  //   }
  // })
  // process.stdin.on('end', () => {
  //   process.stdout.write('结束')
  // })
} else if (signList.includes(argv[2])) {
  if (helpList.includes(argv[2])) return console.log(help)
  fs.writeFileSync('.sign', argv[2], { encoding: 'utf8' })

  if (argv[2] === 'status') {
    setTimeout(() => {
      const rs = JSON.parse(fs.readFileSync('.json', { encoding: 'utf8' }))
      console.log(`${Acan.time('H:i:s', rs.last)} Ping: ${rs.ping}ms 网速: ${Amod.sizeFormat(rs.count.rate)}/s 流量: ${Amod.sizeFormat(rs.count.total)} 内存: ${Amod.sizeFormat(rs.rss)} MTU: ${rs.mtu} Pid: ${rs.pid}`)
    }, 200)
  }
  if (argv[2] === 'test') {
    setTimeout(() => {
      console.log(fs.readFileSync('.json', { encoding: 'utf8' }))
    }, 200)
  }
  return
} else {
  watchFn()
  fs.writeFileSync('.pid', process.pid + '')
  if (argv[2] === 'daemon') {
    const { exec } = require('child_process')
    argv[2] = ''
    exec(process.argv.join(' '))
    process.exit()
  }
  udpSer()
}
